package cn.stylefeng.guns.sys.modular.importHelper;

import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
//import org.jwcloud.project.config.StockUtil;

@RestController
public abstract class BaseExcelHandle implements IBaseExcel{
	
//	/**
//	 * 批量提交数量
//	 */
//	private int batchSize = 10;
	/**
	 * 方言
	 */
	protected String databaseType = "mysql";
	/**
	 * 总配置类
	 */
	private ExcelConfig excelConfig;
	/**
	 * 数据库表宽度
	 */
	private int tableWidth = 1;
	
	@Autowired
    private SqlSessionTemplate sqlSessionTemplate;
	
//	{
//		sqlSessionTemplate = sqlSessionTemplate;// == null ? (SqlSessionTemplate) StockUtil.getBean("sqlSessionTemplate")
////				: sqlSessionTemplate;
//	}
	
	private List submitList = new LinkedList();
	
	/**
	 * 直接返回不提交
	 */
	public static int GO_BREAK_NO_SUBMIT = 0;
	/**
	 * 直接返回并提交
	 */
	public static int GO_BREAK_SUBMIT = 2;
	/**
	 * 跳过本条并继续
	 */
	public static int GO_BREAK_CONTINUE = 3;
	/**
	 * 正常执行下一条
	 */
	public static int GO_CONTINUE = 1;
	
	
	/**
	 * 
	 * @param src excel中的行
	 * @param data 表中的行
	 * @return
	 */
	protected abstract int checkRow(Object[] src, DataStore data, IContext context);
	/**
	 * 校验之前
	 * @param row
	 */
	protected abstract Object beforeHandle();
	/**
	 * 校验之后
	 * @param row
	 */
	protected abstract Object afterHandle();
	
//	protected int doBatchInsert() {
//		return 1;
//	}
	
	private boolean check() {
		return true;
	}
	
	public IContext run(ExcelConfig excelConfig) {
		
		this.excelConfig = excelConfig;
		
		this.init();
		this.check();
		
		IContext context = new Context();
		Map contextData = new HashMap();
		context.setData(contextData);
		
		Object bobj = this.beforeHandle();
		contextData.put("beforeData", bobj);
		
		ProxyExcelRow proxy = new ProxyExcelRow(excelConfig);
		Iterator it = proxy.iterator();
		DataStore dataStore = new DataStore();
		while(it.hasNext()) {
			String[] temp = (String[]) it.next();
			String[] data = new String[this.tableWidth];
			dataStore.setData(data);
			int res = this.checkRow(temp, dataStore, null);
			
			if(res == GO_CONTINUE) {
				//this.submitList.add(temp);
				//System.out.println("整理后data：" + Arrays.toString(dataStore.getData()));
				this.submitList.add(dataStore.getData());
			}else if(res == GO_BREAK_CONTINUE) {
				continue;
			}else if(res == GO_BREAK_NO_SUBMIT) {
				this.submitList = null;
				break;
			}else if(res == GO_BREAK_SUBMIT) {
				break;
			}else {
				throw new RuntimeException("返回值非法");
			}
		}
		
		this.doSubmit();
		
		
		Object aobj = this.afterHandle();
		contextData.put("afterData", aobj);
		
		return context;
	}
	
	private void doSubmit() {
		List list = this.submitList;
		int batchSize = this.excelConfig.getBatchSize();
		Map daoMap = new HashMap(2);
		daoMap.put("tableName", excelConfig.getTableName());
		
		if("mysql".equals(this.databaseType)) {
			if(list == null || list.size() == 0) 
				return;
			
			String tempTableName = (String) daoMap.get("tableName");
			String firstName = tempTableName.substring(0, tempTableName.indexOf("."));
			String endName = tempTableName.substring(tempTableName.indexOf(".") + 1);
			tempTableName = "`" + firstName + "`." + endName;
			daoMap.put("tableName", tempTableName);
			
			StringBuffer sql = new StringBuffer();
			for(int i = 0; i < list.size(); i++) {
				String[] temp = (String[]) list.get(i);
				sql.append(" select ");
				for(String str: temp) {
					sql.append(str == null ? "null, " : "'" + str + "', ");
				}
				
				sql.delete(sql.length() - 2, sql.length()).append(" from dual ");
				
				if(i != 0 && (i + 1) % batchSize == 0) {
					daoMap.put("sql", sql.toString());
					this.sqlSessionTemplate.insert("common.excel.insertImport_mysql", daoMap);
					sql = new StringBuffer();
				}else {
					sql.append(" union all ");
				}
			}
			
			if(sql.length() > 0) {
				sql.delete(sql.length() - " union all ".length(), sql.length());
				daoMap.put("sql", sql.toString());
				this.sqlSessionTemplate.insert("common.excel.insertImport_mysql", daoMap);
			}
			
		}else {
			throw new RuntimeException("目前只支持mysql");
		}
		
	}
	/**
	 * 各种初始化
	 */
	private void init() {
		Map daoMap = new HashMap();
		daoMap.put("tableName", this.excelConfig.getTableName());
		this.tableWidth = Integer.valueOf(this.sqlSessionTemplate.selectOne("common.excel.queryColumnWidth_mysql", daoMap));
	}
	
//	/**
//	 * 一批的数量
//	 * @param batchSize
//	 */
//	public void setBatchSize(int batchSize) {
//		this.batchSize = batchSize;
//	}
	/**
	 * 
	 * @param databaseType
	 */
	public void setDatabaseType(String databaseType) {
		this.databaseType = databaseType;
	}
	public SqlSessionTemplate getSqlSessionTemplate() {
		return sqlSessionTemplate;
	}
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}
	
	
}